package com.itheima.userservice.service;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Service
public class ReadPDFServiceImpl implements ReadPDFService {
    @Override
    public Integer read(int pageNo, int pageSize, HttpServletResponse response) throws IOException {
        Integer size = null;
        Integer start = (pageNo - 1) * pageSize;
        Integer end = pageSize * pageNo;

        //用于缓存传递到前端的pdf页面
        PDDocument pdf = new PDDocument();

        //用于解析读取到的pdf文件
        PDDocument load = null;

        ServletOutputStream outputStream = null;
        try {
            response.setContentType("application/pdf");
            outputStream = response.getOutputStream();

            //解析pdf
            load = PDDocument.load(new File("D:\\test\\nginx.pdf"));

            List allPages = load.getDocumentCatalog().getAllPages();
            size = allPages.size();
            if (size <= end) {
                //最后的页码
                end = size;
            }
            for (int i = start; i < end; i++) {
                PDPage pdPage = (PDPage) allPages.get(i);
                pdf.addPage(pdPage);
            }
            pdf.save(outputStream);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            load.close();
            pdf.close();
            outputStream.close();
        }
        return size;
    }
}
